package com.jiangruan.javaproject.request;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class HttpUtils {

    /*
    该函数用于实现get请求，并将请求的结果进行返回
    @param path请求的资源路径
    @return 请求的结果
*/
    public static String  get(String path) {
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reade = null;

        String line = "";//最开始空行
        String result = "";//每次读取到以后都要积累起来得读取结果
        try {
            //Union Resource Location 统一资源定位
            URL url = new URL(path);
            URLConnection conn = url.openConnection();
            //进行连接
            conn.connect();
             inputStream = conn.getInputStream();
            //字符流：按行读
            inputStreamReader = new InputStreamReader(inputStream);
            reade = new BufferedReader(inputStreamReader);

            while ((line = reade.readLine()) != null) {
                result += line;
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
        //关闭读取流
            try {
            if (reade != null){

                    reade.close();

            }
            if (inputStreamReader != null){
                inputStreamReader.close();
            }
            if (inputStream !=null){
                inputStream.close();
            }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
        }

    }
